import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse, AxiosError, AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'

// Response data structure
export interface ResponseData<T = any> {
  code: number
  data: T
  message: string
}

// Create axios instance
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  withCredentials: true, // 关键配置：允许跨域携带 cookie
  timeout: 15000
})

// Request interceptor
service.interceptors.request.use(
  (config) => {
    // Add token if needed
    const token = localStorage.getItem('token')
    console.log(token)
    if (token) {
      config.headers['Authorization'] = `${token}`
    }
    return config
  },
  (error: AxiosError) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    // Customize based on your API response structure
    // This is an example assuming the API returns { code, data, message }
    if (res.code !== 1 && res.status !== "success" && res.message !== "更新成功" && res.interviewed_count == undefined
      && res.stats == undefined
    ) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      
      // Handle various error codes
      if (res.code === 401 || res.code === 403) {
        // Handle authentication errors
        // e.g., redirect to login
      }
      
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // Return the entire response to let individual API calls handle their data
      return response.data
    }
  },
  (error: AxiosError) => {
    console.error('Response error:', error)
    
    // Handle different HTTP status codes
    const status = error.response?.status
    let message = 'Connection error'
    
    if (status) {
      switch (status) {
        case 400:
          message = 'Bad request'
          break
        case 401:
          message = 'Unauthorized, please login again'
          // Redirect to login or clear credentials
          break
        case 403:
          message = 'Access denied'
          break
        case 404:
          message = 'Request resource not found'
          break
        case 500:
          message = 'Server error'
          break
        default:
          message = `Connection error (${status})`
      }
    }
    
    ElMessage({
      message,
      type: 'error',
      duration: 5 * 1000
    })
    
    return Promise.reject(error)
  }
)

export default service 